package com.fary.rabbitmq.publish_subscribe;

import com.fary.rabbitmq.config.RabbitMQFactory;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author chenyq
 * @date 2023/11/29
 */

public class Producer {
    //几个常量
    private static final String FANOUT_EXCHANGE = "fanoutExchange";
    private static final String FANOUT_QUEUE_1 = "fanoutQueue1";
    private static final String FANOUT_QUEUE_2 = "fanoutQueue2";

    public static void main(String[] args) {

        // 创建连接工厂
        ConnectionFactory factory = RabbitMQFactory.getConnectionFactory();

        // 创建连接
        Connection connection = null;
        // 创建通道
        Channel channel = null;
        try {
            // 创建连接
            connection = factory.newConnection();
            // 创建通道
            channel = connection.createChannel();
            //声明交换机
            channel.exchangeDeclare(FANOUT_EXCHANGE, BuiltinExchangeType.FANOUT, true, false, null);
            // 声明队列
            channel.queueDeclare(FANOUT_QUEUE_1, true, false, false, null);
            channel.queueDeclare(FANOUT_QUEUE_2, true, false, false, null);

            //队列和交换机的相互绑定
            channel.queueBind(FANOUT_QUEUE_1, FANOUT_EXCHANGE, "");
            channel.queueBind(FANOUT_QUEUE_2, FANOUT_EXCHANGE, "");

            String msg = "你在拼多多购买的商品已下单,请及时付款";
            // 发布消息
            channel.basicPublish(FANOUT_EXCHANGE, "", null, msg.getBytes());

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                // 关闭通道
                if (channel != null & connection != null) {
                    channel.close();
                    connection.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

    }

}
